import React, { PureComponent } from 'react';
import {
  BackHandler, Animated, Easing, Alert, DeviceEventEmitter,
} from 'react-native';
import { createStackNavigator } from 'react-navigation';
import SplashScreen from 'react-native-splash-screen';
import MainNavigator from './main';
import { Login, Config, Version } from '../pages';
import { NavigationService } from '../utils';

const AppNavigator = createStackNavigator(
  {
    Main: { screen: MainNavigator },
    Login: { screen: Login },
    Config: { screen: Config },
    Version: { screen: Version },
  },
  {
    initialRouteName: 'Login',
    headerMode: 'none',
    cardStyle: ({
      backgroundColor: 'rgba(0, 0, 0, 0.4)',
    }),
    mode: 'modal',
    navigationOptions: {
      gesturesEnabled: false,
    },
    onTransitionEnd: ({ navigation }) => {
      global.navigation = navigation;
    },
    transitionConfig: () => ({
      transitionSpec: {
        duration: 200,
        easing: Easing.out(Easing.poly(4)),
        timing: Animated.timing,
      },
      screenInterpolator: sceneProps => {
        const { layout, position, scene } = sceneProps;
        const { index } = scene;

        const height = layout.initHeight;
        const translateY = position.interpolate({
          inputRange: [index - 1, index, index + 1],
          outputRange: [height, 0, 0],
        });

        const opacity = position.interpolate({
          inputRange: [index - 1, index - 0.99, index],
          outputRange: [0, 1, 1],
        });

        return { opacity, transform: [{ translateY }] };
      },
    }),
  },
);

export const getActiveRouteName = (navigationState) => {
  if (!navigationState) {
    return null;
  }
  if (navigationState.index !== undefined) {
    const route = navigationState.routes[navigationState.index];
    if (route) {
      return getActiveRouteName(route);
    }
  }
  return navigationState.routeName;
};

class Router extends PureComponent {
  componentDidMount() {
    // SplashScreen.hide();// 让splash页面消失
    BackHandler.addEventListener('hardwareBackPress', this._backHandle);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this._backHandle);
  }

  _routeHandle = ({ routeName }) => {
    if (this.navigator) {
      if (routeName === 'Main') {
        NavigationService.back();
      }
      NavigationService.navigate(routeName);
    }
  }

  _showExitAlert = () => {
    Alert.alert(
      '提示',
      '是否真的要退出应用?',
      [
        { text: '取消', style: 'cancel' },
        {
          text: '确定',
          onPress: () => {
            BackHandler.exitApp();
          },
        },
      ],
    );
  }

  _backHandle = () => {
    if (global.navigation) {
      const currentScreen = getActiveRouteName(global.navigation.state);
      if (currentScreen === 'Login') {
        BackHandler.exitApp();
        return true;
      }
      if (currentScreen === 'MainView') {
        if (global.mainIndex === 0) {
          DeviceEventEmitter.emit('swiperIncidentPageEvent', 1);
        } else if (global.mainIndex === 2) {
          DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
        } else {
          this._showExitAlert();
        }
        return true;
      }

      if (currentScreen === 'AddIncident') {
        DeviceEventEmitter.emit('saveInfoEvent');
        return true;
      }
    } else {
      this._showExitAlert();
      return true;
    }
    return false;
  }


  render() {
    return (
      <AppNavigator ref={navigatorRef => {
        NavigationService.setTopLevelNavigator(navigatorRef);
      }}
      />
    );
  }
}

export default Router;
